/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package JDBC;

import Logger.MyLogger;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author marcy
 */
public class Operazioni {

    public static Connection connect(String host, int port, String dbName, String User, String pwd) {
        Connection dbConnection = null;

        //Connessione database
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            String dbString = "jdbc:mysql://" + host +":"+ port +"/" + dbName;
            dbConnection = (Connection) DriverManager.getConnection(dbString, User, pwd);
            return dbConnection;
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Operazioni.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(Operazioni.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(Operazioni.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Operazioni.class.getName()).log(Level.SEVERE, null, ex);
        }
        MyLogger.getLogger().debug("");

        return dbConnection;




    }

    public static void disconnect(Connection conn) {
        try {
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(Operazioni.class.getName()).log(Level.SEVERE, null, ex.getMessage());
        }
    }

    public static ResultSet execute_query(String query, Connection conn) {
        ResultSet res = null;
        if(conn == null)
            try {
            conn = ConnectionPool.getConnetionPool().getConnection();
        } catch (ConnectionPoolException ex) {
            Logger.getLogger(Operazioni.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            Statement stm = (Statement) conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            res = (ResultSet) stm.executeQuery(query);
        } catch (SQLException ex) {
            Logger.getLogger(Operazioni.class.getName()).log(Level.SEVERE, null, ex);
        }
        MyLogger.getLogger().debug("ExecuteQuery");
        return res;
    }
    public static void execute_statement (String query, Connection conn){
        try {
            Statement stmt = (Statement) conn.createStatement();
            stmt.execute(query);
            stmt.close();
            MyLogger.getLogger().debug("ExecuteStatement");
        } catch (SQLException ex) {
            Logger.getLogger(Operazioni.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
